package services

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"net/http"
	"sort"
	"strings"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/core/logs"
)

// BaseMeituanService 美团基础服务
type BaseMeituanService struct {
	BaseURL    string
	AppKey     string
	AppSecret  string
	PoiId      string
	HTTPClient *http.Client
}

// NewBaseMeituanService 创建美团基础服务实例
func NewBaseMeituanService(appKey, appSecret, poiId string) *BaseMeituanService {
	return &BaseMeituanService{
		BaseURL: "https://api.meituan.com",
		AppKey:  appKey,
		AppSecret: appSecret,
		PoiId:   poiId,
		HTTPClient: &http.Client{
			Timeout: time.Second * 10,
		},
	}
}

// generateSign 生成签名
func (s *BaseMeituanService) generateSign(params map[string]string) string {
	// 按键排序
	var keys []string
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 拼接参数
	var pairs []string
	for _, k := range keys {
		pairs = append(pairs, fmt.Sprintf("%s=%s", k, params[k]))
	}
	paramStr := strings.Join(pairs, "&")

	// 添加密钥
	signStr := paramStr + "&key=" + s.AppSecret

	// MD5加密
	hash := md5.Sum([]byte(signStr))
	return strings.ToUpper(fmt.Sprintf("%x", hash))
}

// makeRequest 发送HTTP请求
func (s *BaseMeituanService) makeRequest(method, endpoint string, params map[string]string, result interface{}) error {
	urlStr := fmt.Sprintf("%s%s", s.BaseURL, endpoint)
	
	// 添加基本参数
	if params == nil {
		params = make(map[string]string)
	}
	params["app_key"] = s.AppKey
	params["timestamp"] = fmt.Sprintf("%d", time.Now().Unix())
	params["sign"] = s.generateSign(params)

	var resp *http.Response
	var err error

	if method == "GET" {
		// 构建查询参数
		queryParams := make([]string, 0)
		for k, v := range params {
			queryParams = append(queryParams, fmt.Sprintf("%s=%s", k, v))
		}
		if len(queryParams) > 0 {
			urlStr = urlStr + "?" + strings.Join(queryParams, "&")
		}
		resp, err = s.HTTPClient.Get(urlStr)
	} else if method == "POST" {
		formData := make(map[string][]string)
		for k, v := range params {
			formData[k] = []string{v}
		}
		resp, err = s.HTTPClient.PostForm(urlStr, formData)
	}

	if err != nil {
		return fmt.Errorf("HTTP请求失败: %v", err)
	}
	defer resp.Body.Close()

	if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
		return fmt.Errorf("解析响应失败: %v", err)
	}

	return nil
}

// GetOrders 获取订单列表
func (s *BaseMeituanService) GetOrders(startTime, endTime time.Time, orderType string) ([]map[string]interface{}, error) {
	params := map[string]string{
		"start_time": startTime.Format("2006-01-02 15:04:05"),
		"end_time":   endTime.Format("2006-01-02 15:04:05"),
		"poi_id":     s.PoiId,
		"order_type": orderType,
	}

	var result struct {
		Code int                      `json:"code"`
		Msg  string                   `json:"msg"`
		Data []map[string]interface{} `json:"data"`
	}

	if err := s.makeRequest("GET", "/api/v1/orders", params, &result); err != nil {
		return nil, err
	}

	if result.Code != 0 {
		return nil, fmt.Errorf("API返回错误: %s", result.Msg)
	}

	return result.Data, nil
}

// GetOrderDetail 获取订单详情
func (s *BaseMeituanService) GetOrderDetail(orderId string) (map[string]interface{}, error) {
	params := map[string]string{
		"order_id": orderId,
		"poi_id":   s.PoiId,
	}

	var result struct {
		Code int                    `json:"code"`
		Msg  string                 `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}

	if err := s.makeRequest("GET", "/api/v1/order/detail", params, &result); err != nil {
		return nil, err
	}

	if result.Code != 0 {
		return nil, fmt.Errorf("API返回错误: %s", result.Msg)
	}

	return result.Data, nil
}

// UseVoucher 使用券码
func (s *BaseMeituanService) UseVoucher(orderId, voucherCode string) error {
	params := map[string]string{
		"order_id":     orderId,
		"voucher_code": voucherCode,
		"poi_id":       s.PoiId,
	}

	var result struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
	}

	if err := s.makeRequest("POST", "/api/v1/voucher/use", params, &result); err != nil {
		return err
	}

	if result.Code != 0 {
		return fmt.Errorf("API返回错误: %s", result.Msg)
	}

	return nil
}

// CancelOrder 取消订单
func (s *BaseMeituanService) CancelOrder(orderId string, reason string) error {
	params := map[string]string{
		"order_id": orderId,
		"poi_id":   s.PoiId,
		"reason":   reason,
	}

	var result struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
	}

	if err := s.makeRequest("POST", "/api/v1/order/cancel", params, &result); err != nil {
		return err
	}

	if result.Code != 0 {
		return fmt.Errorf("API返回错误: %s", result.Msg)
	}

	return nil
}

// SyncOrders 同步订单数据
func (s *BaseMeituanService) SyncOrders(startTime, endTime time.Time) ([]map[string]interface{}, error) {
	orders, err := s.GetOrders(startTime, endTime, "group")
	if err != nil {
		logs.Error("从美团API获取团购订单失败: %v", err)
		return nil, err
	}

	return orders, nil
}

// GetMeituanServiceByStoreId 根据门店ID获取美团服务实例
func GetMeituanServiceByStoreId(storeId int64) (*BaseMeituanService, error) {
	meituanConfig, err := models.GetMeituanByStoreId(storeId)
	if err != nil {
		return nil, fmt.Errorf("获取美团配置失败: %v", err)
	}
	if meituanConfig == nil {
		return nil, fmt.Errorf("未找到美团配置")
	}

	return NewBaseMeituanService(meituanConfig.AppKey, meituanConfig.AppSecret, meituanConfig.PoiId), nil
}